import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { ImageUploader, Toast } from 'antd-mobile';
import { fetchOSS } from '@/services/oss';

interface UploadOssProps {
  isVisible?: boolean;
  onSetFilesURL: (value: string) => void;
}

const UploadOss: React.FC<UploadOssProps> = (props) => {
  const [OSSData, setOSSData] = useState<any>({});
  const [fileList, setFileList] = useState<any[]>([]);
  const { children, onSetFilesURL, isVisible } = props;

  useEffect(() => {
    setFileList([]);
  }, [isVisible]);

  const init = useCallback(async () => {
    try {
      const data = await fetchOSS();
      setOSSData(data);
    } catch (error: any) {
      console.error(error);
    }
  }, []);

  useEffect(() => {
    init();
    return () => {
      setOSSData({});
    };
  }, []);

  const handleChange = useCallback(
    ({ fileList }: any) => {
      setFileList(fileList);
      if (fileList[0]?.status === 'done') {
        Toast.show({
          icon: 'success',
          content: '上传成功',
        });
        const value = fileList[0].url;
        onSetFilesURL(value);
      }
    },
    [onSetFilesURL],
  );

  const getExtraData = useCallback(
    (file: any) => {
      return {
        key: file.key,
        OSSAccessKeyId: OSSData.accessid,
        policy: OSSData.policy,
        Signature: OSSData.signature,
      };
    },
    [OSSData],
  );

  const handlebeforeUpload = useCallback(
    async (file: any) => {
      const expire = OSSData.expire * 1000;

      if (expire < Date.now()) {
        init();
      }

      const dir = 'ayao/';
      const suffix = file.name.slice(file.name.lastIndexOf('.'));
      const filename = Date.now() + suffix;
      file.key = dir + OSSData.dir + filename;
      file.url = OSSData.host + OSSData.dir + dir + filename;

      return file;
    },
    [OSSData, init, Date],
  );

  const Uploadprops: any = useMemo(
    () => ({
      name: 'file',
      fileList,
      action: OSSData.host,
      maxCount: 1,
      onChange: handleChange,
      data: getExtraData,
      beforeUpload: handlebeforeUpload,
    }),
    [OSSData, handleChange, getExtraData, handlebeforeUpload, fileList],
  );
  return <ImageUploader {...Uploadprops}>{children}</ImageUploader>;
};

export default UploadOss;
